package org.jeecg.modules.flow.callback.inbound.other;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.basic.material.entity.BasicMaterial;
import org.jeecg.modules.basic.material.mapper.BasicMaterialMapper;
import org.jeecg.modules.basic.plant.entity.WmsSapWarehouseMap;
import org.jeecg.modules.basic.plant.mapper.WmsSapWarehouseMapMapper;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouse;
import org.jeecg.modules.basic.warehouse.mapper.WmsBasicWarehouseMapper;
import org.jeecg.modules.business.transfer.entity.PaperPurchase;
import org.jeecg.modules.business.transfer.entity.PaperPurchaseMaterial;
import org.jeecg.modules.business.transfer.mapper.PaperPurchaseMapper;
import org.jeecg.modules.business.transfer.service.IPaperPurchaseMaterialService;
import org.jeecg.modules.dock.entity.dto.request.PaperPurchaseRequestDTO;
import org.jeecg.modules.dock.entity.dto.response.PaperPurchaseResponseDTO;
import org.jeecg.modules.dock.service.SapDockingRepeaterService;
import org.jeecg.modules.flow.sys.common.BaseCustomBeanRun;
import org.jeecg.modules.flow.sys.entity.dto.BaseFlowDto;
import org.jeecg.modules.flow.sys.exception.FlowCurrentFailException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 纸筒采购任务发送sap
 *
 * @author lumingyi
 * @version 1.0.0
 * @since 2023-11-15
 */
@Component
@Slf4j
public class R47PaperPurchaseSendBeforeBean<T> extends BaseCustomBeanRun<T> {
    @Autowired
    private PaperPurchaseMapper paperPurchaseMapper;
    @Autowired
    private IPaperPurchaseMaterialService paperPurchaseMaterialService;
    @Autowired
    private SapDockingRepeaterService sapDockingRepeaterService;
    @Autowired
    private BasicMaterialMapper basicMaterialMapper;
    @Autowired
    private WmsSapWarehouseMapMapper sapWarehouseMapMapper;
    @Autowired
    private WmsBasicWarehouseMapper warehouseMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void actureRun() {
        log.info("纸筒采购任务发送sap开始");
        BaseFlowDto baseFlowDto = this.getBaseFlowDto();
        List<PaperPurchaseRequestDTO> list = new ArrayList<>();
        List<PaperPurchaseMaterial> materials = paperPurchaseMaterialService.selectByMainId(baseFlowDto.getInfoId());
        for (PaperPurchaseMaterial material : materials) {
            PaperPurchaseRequestDTO dto = new PaperPurchaseRequestDTO();
            BasicMaterial basicMaterial = basicMaterialMapper.selectById(material.getWmsBasicMaterialId());
            dto.setMaterial(basicMaterial.getCode());
            WmsSapWarehouseMap one = sapWarehouseMapMapper.selectOne(new LambdaQueryWrapper<WmsSapWarehouseMap>()
                    .eq(WmsSapWarehouseMap::getWmsBasicWarehouseId, material.getWmsBasicWarehouseId())
                    .last("limit 1"));
            if (one == null) {
                throw new JeecgBootException("发送失败，仓库为空或没有配置对应的sap库位");
            }
            dto.setFactory(one.getSapLocation());
            dto.setPurchaseQuantity(new BigDecimal(material.getPurchaseQuantity()));
            list.add(dto);
        }

        List<PaperPurchaseResponseDTO> responseDTOS = new ArrayList<>();
        try {
            responseDTOS = sapDockingRepeaterService.sapPushPaperPurchase(list);
        }catch (Exception e){
            baseFlowDto.setCurrentFailed(true);
            baseFlowDto.setResult(Result.error("纸筒采购任务发送sap失败: "+e.getMessage()));
            throw new FlowCurrentFailException("纸筒采购任务发送sap失败: " + e.getMessage());
        }
        log.info("纸筒采购任务发送sap结束 响应: {}", responseDTOS);
        if (CollectionUtil.isNotEmpty(responseDTOS)) {
            PaperPurchaseResponseDTO res = responseDTOS.get(0);
            if ("E".equals(res.getResult())) {
                baseFlowDto.setCurrentFailed(true);
                baseFlowDto.setResult(Result.error(res.getMessage()));
                throw new FlowCurrentFailException("纸筒采购任务发送sap失败: " + res.getMessage());
            }
        }
        //将状态改为已发送
        PaperPurchase po = paperPurchaseMapper.selectById(baseFlowDto.getInfoId());
        po.setDocumentStatus("3");
        paperPurchaseMapper.updateById(po);
        log.info("纸筒采购任务发送sap结束");
        baseFlowDto.setResult(Result.ok("操作成功"));
    }
}
